package seatiger.tomcat.coyote;

import seatiger.tomcat.coyote.http11.InternalOutputBuffer;
import seatiger.tomcat.util.buf.ByteChunk;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * coyote Response
 */
public final class Response {

    /**
     * 响应码
     */
    protected int status = 200;
    /**
     * 相应信息
     */
    protected String message = null;


    protected OutputBuffer outputBuffer;

    /**
     * 发送长度
     */
    protected int contentLength = -1;

    /**
     * 输出的报文头
     */
    protected Map<String, String> headers = new HashMap<>();

    /**
     * 钩子函数
     */
    protected ActionHook hook;

    protected boolean commited = false;

    public boolean isCommited() {
        return commited;
    }

    public void setCommited(boolean commited) {
        this.commited = commited;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public void setHook(ActionHook hook) {
        this.hook = hook;
    }

    public void setOutputBuffer(OutputBuffer outputBuffer) {
        this.outputBuffer = outputBuffer;
    }

    public int getStatus() {
        return status;
    }

    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }

    public int getContentLength() {
        return contentLength;
    }

    public void addHeader(String name, String value) {
        headers.put(name, value);
    }

    public void finish() throws IOException {
        action(ActionCode.ACTION_CLOSE);
    }

    public void doWrite(ByteChunk chunk) throws IOException{
        outputBuffer.doWrite(chunk, this);
    }

    public void recycle() {
        contentLength = -1;
        status = 200;
        message = null;
        headers.clear();
        commited = false;
    }

    /**
     * 发送报文头信息
     * @throws IOException
     */
    public void sendHeaders() throws IOException {
        //回调钩子方法
        action(ActionCode.ACTION_COMMIT);
        commited = true;
    }


    public void action(ActionCode actionCode){
        hook.action(actionCode,this);
    }
}
